from django.shortcuts import render,redirect,reverse
from django.views.generic import View
from django.contrib.auth import authenticate,login,logout
from apps.user.models import *

# Create your views here.

class LoginView(View):
    def get(self,request):

        # print(request.GET.get('username'))

        return render(request,'Login.html')

    def post(self,request):
        #获取信息
        user_name = request.POST.get('username')
        password = request.POST.get('password')
        user = authenticate(username=user_name, password=password)
        if user is not None:
            if user.is_active:
                login(request, user)
                # 获取登录后索要跳转的地址
                # 默认跳转到首页
                # next_url = request.GET.get('next', reverse('goods:index'))
                response = redirect(reverse('goods:index'))
                remember = request.POST.get('remember')
                # 判断是否记住用户名
                if remember == 'on':
                    # 记住
                    print('1')
                    response.set_cookie('username', user_name, max_age=7 * 24 * 3600)
                else:
                    print('2')
                    response.delete_cookie('username')
                print('ok')
                return response
            else:
                return redirect(reverse('user:login'))
        else:
            # return render(request,'Login.html')
            return redirect(reverse('user:login'))


class LoginoutView(View):

    def get(self,request):
        # 清楚用户信息
        logout(request)

        return redirect(reverse('user:login'))












